package com.pers.springcloud.controller;

import lombok.AllArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;
import java.util.List;

@RestController
@AllArgsConstructor
public class ServerController {

    private final LoadBalancerClient loadBalancerClient;
    private final DiscoveryClient discoveryClient;

    @GetMapping("/services")
    public ResponseEntity<List<String>> getServices(){
        List<String> services = discoveryClient.getServices();
        return ResponseEntity.ok().body(services);
    }

    @GetMapping("/services/instances")
    public ResponseEntity<List<ServiceInstance>> getServiceInstance(){
        List<ServiceInstance> instances = discoveryClient.getInstances("service-producer");
        return ResponseEntity.ok().body(instances);
    }

    @GetMapping("/discover")
    public ResponseEntity<String> discover() {
        URI uri = loadBalancerClient.choose("service-producer").getUri();
        return ResponseEntity.ok().body(uri.toString());
    }
}
